package pers.cj.pdos.controller;


import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ResponseBody;
import pers.cj.pdos.controller.base.BaseController;
import pers.cj.pdos.controller.entity.RequestRolePermission;
import pers.cj.pdos.controller.entity.ResponseData;
import pers.cj.pdos.controller.entity.ResponseEntity;
import pers.cj.pdos.controller.entity.ResponseList;
import pers.cj.pdos.entity.*;
import pers.cj.pdos.service.*;
import pers.cj.pdos.utils.DataUtil;
import pers.cj.pdos.utils.Utils;
import pers.cj.pdos.utils.UuidUtils;
import pers.cj.pdos.vo.menu.Menu1Vo;
import pers.cj.pdos.vo.menu.Menu2Vo;
import pers.cj.pdos.vo.role.rolePermission.QueryPermission;
import pers.cj.pdos.vo.role.rolePermission.QueryRolePermission;

import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author chenj
 * @since 2019-11-04
 */
@Controller
@RequestMapping("/user")
public class RoleController extends BaseController {
    @Autowired
    private IRoleService roleService;
    @Autowired
    private IPermissionService permissionService;
    @Autowired
    private IMenu1Service menu1Service;
    @Autowired
    private IRolePermissionService rolePermissionService;

    @RequiresPermissions("role:query")
    @RequestMapping("/role")
    public String role(){
        return "user/role";
    }

    @ResponseBody
    @RequiresPermissions("role:query")
    @RequestMapping("/role/getRoles")
    public ResponseList getRoles(int page, int limit) {
        Company company = getCompany();
        List<Role> list = roleService.listPage(company.getId(),page,limit);
        return ResponseList.success(roleService.count(company.getId()),list );
    }

    @ResponseBody
    @RequiresPermissions("role:insert")
    @RequestMapping("/role/add")
    public ResponseEntity add(@RequestBody Role role){
        Company company = getCompany();
        if (roleService.checkName(role.getName(),company.getId())){
            return ResponseEntity.fail("角色名称已存在");
        }
        DataUtil.processEntity(company, role);

        roleService.add(role);
        return ResponseEntity.success();
    }

    @ResponseBody
    @RequiresPermissions("role:delete")
    @RequestMapping("/role/delete")
    public ResponseEntity delete(@RequestBody Role role){
        try {
            roleService.remove(role);
            return ResponseEntity.success();
        } catch (Exception e) {
            return ResponseEntity.fail("已被使用无法删除");
        }
    }

    @ResponseBody
    @RequiresPermissions("role:insert")
    @RequestMapping("/role/update")
    public ResponseEntity update(@RequestBody Role role, Boolean checkName){
        if (checkName && roleService.checkName(role.getName(),getCompany().getId())){
            return ResponseEntity.fail("角色名称已存在");
        }
        DataUtil.processEntity(false,getCompany(), role);
        roleService.update(role);
        return ResponseEntity.success();
    }

    @RequiresPermissions("role:insert")
    @RequestMapping("/role/rolePermission")
    public String rolePermission(Model model,String roleId){
        model.addAttribute("roleId",roleId);
        return "user/rolePermission";
    }

    @ResponseBody
    @RequestMapping("role/getById")
    public ResponseData getById(String id){
        Role role = roleService.getOne(id);
        return ResponseData.success(role);
    }

    @ResponseBody
    @RequiresPermissions("role:insert")
    @RequestMapping("/role/getPermissions")
    public ResponseList getPermissions(String roleId) {
        Company company = getCompany();
        //获取角色已有的权限,并放到map中
        List<RolePermission> list = rolePermissionService.listByRole(roleId,company.getId());
        Map<String,RolePermission> map = new HashMap<>();
        for (RolePermission rolePermission:list){
            map.put(rolePermission.getPermissionId(),rolePermission);
        }


        int type = getIndustryType().getType();
        List<QueryRolePermission> queryRolePermissions = new ArrayList<>();


        Map<String, List<Permission>> groupByNameMap = new HashMap<>();
        List<Permission> permissionList = permissionService.listAll();
        for (Permission permission : permissionList) {
            String groupName = permission.getGroupName();
            if(groupByNameMap.containsKey(groupName)) {
                //如果Map中的key包含此时的groupName,则取出Value,直接add此实体
                groupByNameMap.get(groupName).add(permission);
            }else {
                //否则的话,新建一个key为groupName的List,并将groupName作为key,list作为value放入map
                List<Permission> groupPermissionList = new ArrayList<>();
                groupPermissionList.add(permission);
                groupByNameMap.put(groupName, groupPermissionList);
            }
        }

        List<Menu1Vo> menu1VoList = menu1Service.listVo(null);
        for (Menu1Vo menu1Vo : menu1VoList) {
            for (Menu2Vo menu2Vo : menu1Vo.getMenu2VoList()) {
                for (Menu3 menu3 : menu2Vo.getMenu3List()) {
                    if (Utils.isEmpty(menu3.getGroupName())) continue;
                    if (menu3.getName().equals("序列号查询") && type != 2) continue;
                    if (menu3.getName().equals("保质期批次") && type != 1) continue;

                    QueryRolePermission queryRolePermission = new QueryRolePermission();
                    queryRolePermission.setLevel1(menu1Vo.getName());
                    queryRolePermission.setLevel2(menu3.getName());

                    List<Permission> permissions = groupByNameMap.get(menu3.getGroupName());
                    List<QueryPermission> queryPermissions = new ArrayList<>();
                    for (Permission permission:permissions){
                        QueryPermission queryPermission = new QueryPermission();
                        queryPermission.setId(permission.getId());
                        queryPermission.setCode(permission.getCode());
                        queryPermission.setName(permission.getName());
                        //map中存放的是角色包含的所有权限的id，如果当前权限id在map中，表示已经被选中
                        queryPermission.setChecked(map.containsKey(permission.getId()) ? "checked" : "");

                        queryPermissions.add(queryPermission);
                    }

                    queryRolePermission.setQueryPermissionList(queryPermissions);
                    queryRolePermissions.add(queryRolePermission);
                }
            }
        }

        return ResponseList.success(queryRolePermissions.size(), queryRolePermissions);
    }

    @ResponseBody
    @RequiresPermissions("role:insert")
    @RequestMapping("/role/updateRolePermission")
    public ResponseEntity updateRolePermission(String roleId, @RequestBody List<RolePermission> rolePermissionList){
        Company company = getCompany();
        DataUtil.processList(company,rolePermissionList);
        rolePermissionService.updateList(rolePermissionList,roleId,company.getId());
        return ResponseEntity.success();
    }

    @ResponseBody
    @RequestMapping("/role/listWithoutAdmin")
    public ResponseData listWithoutAdmin(){
        List<Role> roleList = roleService.listWithoutAdmin(getCompany().getId());
        return ResponseData.success(roleList);
    }
}
